package com.hzqy.commons.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.security.MessageDigest;
import java.util.*;

public class YZFUtil {
	private static final Log LOG = LogFactory.getLog(YZFUtil.class);
	private static boolean KEY_SWITCH = true;//true 开启密钥验证 ；false 关闭密钥验证
	//private static String KEY= "jhzfItvPay2020";
	private static String KEY= SystemConfigUtils.getSysConfig("yzfKey");
	public static void main(String[] args){

	}
	
	public static String getSysKey(String partnerName,String productId,String storeCode,String systemid) {
		if(KEY_SWITCH){
			Map<String,Object> signParams = new HashMap<String,Object>();
			signParams.put("partnerName", partnerName);
			signParams.put("productId", productId);
			signParams.put("storeCode", storeCode);
			signParams.put("systemid", systemid);

			LOG.debug("partnerName:"+partnerName);
			LOG.debug("productId:"+productId);
			LOG.debug("storeCode:"+storeCode);
			LOG.debug("systemid:"+systemid);

			String sysKey = getSign(signParams,KEY);
			String subSysKey = md5(sysKey);
			LOG.debug("最终密钥:"+subSysKey);
			return subSysKey;
		}else{
			return "";
		}
		
	}

	
	public static String getSign(Map<String,Object> signParams,String appSecret){
		//2.1 获取signParams中的key值
		StringBuilder sb = new StringBuilder();
		List<String> keyList = new ArrayList<String> (signParams.size());
		for (Map.Entry entry : signParams.entrySet()) {
			keyList.add((String) entry.getKey());
		}
		//2.2将key值进行排序
		Collections.sort(keyList);

		//2.3 按照该方式拼接成字符串 appSecret+key+map.get(key)+appSecret
		for (String key : keyList) {
			sb.append(key.toLowerCase()).append("=").append(signParams.get(key)).append("&");
		}
		sb.append("key=").append(appSecret);
		//LOG.debug(sb.toString());
		//2.4 SHA1 加密后 将二进制输出为字符串
		return sb.toString();
	}

	public static String md5(String toMd5) {
		if (!StringUtils.isNotEmpty(toMd5)) {
			return null;
		}
		return toString(md5Private(toMd5.getBytes())).toUpperCase();
	}

	/**
	 * 进行md5运算
	 *
	 * @param cs
	 * @return
	 */
	private static byte[] md5Private(byte[] cs) {
		byte[] rs = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			rs = md.digest(cs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}

	public static String toString(byte[] a) {
		if (a == null)
			return "null";
		if (a.length == 0)
			return "";

		StringBuilder buf = new StringBuilder();

		for (int i = 0; i < a.length; i++) {
			if (a[i] < 0)
				buf.append(Integer.toHexString(a[i] & 0xff));
			else if (a[i] < 16) {
				buf.append('0');
				buf.append(Integer.toHexString(a[i]));
			} else {
				buf.append(Integer.toHexString(a[i]));
			}
		}

		return buf.toString();
	}


}
